﻿using CPPEI.Coolzon.UI.Script;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CPPEI.Coolzon.UI
{
    public partial class Part
    {
        private object _scriptObj;

        /// <summary>
        /// 获取脚本可以访问的对象
        /// </summary>
        /// <returns></returns>
        public object GetScriptObj()
        {
            if (_scriptObj == null)
            {
                _scriptObj = OnCreateScriptObj();
            }
            return _scriptObj;
        }

        protected virtual object OnCreateScriptObj()
        {
            return new PartScriptObject(this);
        }

        /// <summary>
        /// 触发脚本事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="data"></param>
        public void RaiseScriptEvent(string eventName, object data)
        {
            this.Dispatcher.Invoke(() =>
            {
                // 调用脚本
                if (HasScriptEvent(eventName))
                {
                    this.InvokeScriptEvent(PartContext.ScriptEngine, eventName, this.GetScriptObj(), data);
                }
                else
                {
                    Common.Logger.WarningToTag("Script", "组件:{0}不含有事件:{1}", this.Name, eventName);
                }
            });
        }
    }
}
